package cn.gemframe.service.impl;

import cn.gemframe.exception.GemException;
import cn.gemframe.exception.status.GemErrorStatus;
import cn.gemframe.config.mail.GemMailProperties;
import cn.gemframe.service.GemSendMailService;
import cn.gemframe.utils.GemStringUtlis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Component
public class GemSendMailServiceImpl implements GemSendMailService {

	@Autowired
	private GemMailProperties mailConfig;

	@Async
	public void sendMailService(String title,String toUser,String context) {
		if(mailConfig == null) {
			throw new GemException(GemErrorStatus.MAIL_CONFIG_ISNULL);
		}
		String mailHost = mailConfig.getHost();
		if(GemStringUtlis.isBlank(mailHost) || mailHost.equalsIgnoreCase("null") || mailHost.length()==0) {
			throw new GemException(GemErrorStatus.MAIL_HOST_ISNULL);
		}
		String mailUserName = mailConfig.getUsername();
		if(GemStringUtlis.isBlank(mailUserName) || mailUserName.equalsIgnoreCase("null") || mailUserName.length()==0) {
			throw new GemException(GemErrorStatus.MAIL_USERNAME_ISNULL);
		}
		String mailUserPassword = mailConfig.getPassword();
		if(GemStringUtlis.isBlank(mailUserPassword) || mailUserPassword.equalsIgnoreCase("null") || mailUserPassword.length()==0) {
			throw new GemException(GemErrorStatus.MAIL_PASSWORD_ISNULL);
		}
		try {
	        Properties prop = new Properties();
	        prop.setProperty("mail.host", mailHost);
	        prop.setProperty("mail.transport.protocol", "smtp");
	        prop.setProperty("mail.smtp.auth", "true");
	        Session session = Session.getInstance(prop);
	        session.setDebug(true);
			Transport ts = session.getTransport();
	        ts.connect(mailHost, mailUserName, mailUserPassword);
	        MimeMessage message = new MimeMessage(session);
	        message.setFrom(new InternetAddress(mailUserName));
	        message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress(toUser)});
	        message.setSubject(title);
	        message.setContent(context, "text/html;charset=UTF-8");
	        ts.sendMessage(message, message.getAllRecipients());
	        ts.close();
		} catch (Exception e) {
			throw new GemException(GemErrorStatus.SEND_MAIL);
		}
	}
}
